package com.wanlong.utils.crypto;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 * @author 万龙
 */
public class _MD5 {
    protected static char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    protected  static MessageDigest messageDigest = null;
    static{
        try{
            messageDigest = MessageDigest.getInstance("MD5");
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
    }

    private static String bufferToHex(byte[] digest) {
        return bufferToHex(digest,0,digest.length);
    }

    private static String bufferToHex(byte[] digest,int m ,int n) {
        StringBuffer stringBuffer = new StringBuffer(2 * n);
        int k = m + n;
        for(int l = m ; l < k ; l++){
            appendHexPair(digest[l],stringBuffer);
        }
        return stringBuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringBuffer){
        //取字节高4位的数字进行转换,逻辑右移，将符号位一起右移
        char c0 = hexDigits[(bt & 0xf0) >>4];
        //取字节低四位的数字转换
        char c1 = hexDigits[bt & 0xf];
        stringBuffer.append(c0);
        stringBuffer.append(c1);
    }

    /**
     * 将字符串用MD5加密并返回
     * @return
     */
    public static String getMD5String(String str){
        if(StringUtils.isEmpty(str)){
            return "";
        }
        byte[] buffer = str.getBytes();
        messageDigest.update(buffer);
        return bufferToHex(messageDigest.digest());
    }


    public static void main(String[] args) {
        //TEST
        System.out.println(_MD5.getMD5String("123456"));
    }
}
